<template>
  <el-card class='box-card'>
    <el-form ref='form' :model='form' :rules='rules' size='mini' label-width='100px' style='width:400px'>
      <el-form-item prop="avatar">
        <img-upload :imageUrl='form.avatar' :showTip='false' @imageUrlChange='imageUrlChange'></img-upload>
      </el-form-item>
      <el-form-item label='用户名' prop="username">
        <el-input v-model='form.username'></el-input>
      </el-form-item>
      <el-form-item label='手机号' prop="mobile">
        <el-input type="tel" v-model='form.mobile'></el-input>
      </el-form-item>
      <el-form-item label='邮箱' prop="email">
        <el-input type="email" v-model='form.email'></el-input>
      </el-form-item>
      <el-form-item label='新密码' prop="password">
        <el-input type='password' v-model='form.password'></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type='primary' @click='submit'>提交</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { get_info, remove_info } from '@/utils/info';
import { remove_token } from '@/utils/token';
import { update_user } from '@/api/auth';
import { validatePhone, validEmail } from '@/utils/validata';

export default {
  name: 'my',
  data() {
    return {
      form: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        email: [
          { required: true, validator: validEmail, trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.form = get_info()
  },
  methods: {
    imageUrlChange(url) {
      this.form.avatar = url
    },
    submit() {
      //确认
      this.$confirm('确认修改吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const valid = await this.$refs["form"].validate;
        if (valid) {
          //提交
          if (!this.form.password) {
            this.form.password = null
          }
          const res = await update_user(this.form);
          this.$message.success(res)
          remove_info()
          remove_token()
          this.$router.push('/login')
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
.box-card {
  width: 30%;
  margin: 0 auto;
  margin-top: 100px;
}
</style>
